package presenter.md5;

import main.InputBean;
import utils.OnLogListener;
import utils.FileBean;
import utils.FileFilter;
import utils.ThreadPool;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.CountDownLatch;

public class MD5Parser {
    private InputBean info;
    private OnLogListener listener;

    public static void parse(InputBean info, OnLogListener listener) {
        ThreadPool.work(() -> {
            MD5Parser parser = new MD5Parser();
            parser.info = info;
            parser.listener = listener;
            parser.action();
        });
    }

    private void action() {
        listener.log("任务开始!");
        List<FileBean> items = FileFilter.filter(true, info.path1(), name -> true);
        if (items == null || items.isEmpty()) {
            listener.log("文件夹为空,任务结束!");
            listener.taskFinish();
        } else {
            Collections.sort(items, Comparator.comparing(FileBean::name));
            listener.log(String.format("文件统计完毕,共%d个文件,开始文件MD5,时间较长,请稍等...", items.size()));
            CountDownLatch latch = new CountDownLatch(items.size());
            for (FileBean item : items) {
                ThreadPool.work(() -> {
                    listener.log(String.format("文件-%s-开始MD5...", item.name()));
                    item.reKey();
                    listener.log(String.format("文件-%s-MD5结束,还剩%d个", item.name(), (latch.getCount() - 1)));
                    latch.countDown();
                });
            }
            try {
                latch.await();
                listener.log("所有文件MD5完成...");
                listener.log("------------------------------我是分割线------------------------------");
                for (FileBean item : items) {
                    listener.log(String.format("文件 %s, MD5 = %s", item.name(), item.md5()));
                }
            } catch (InterruptedException e) {
                listener.log(e.getMessage());
            } finally {
                listener.taskFinish();
            }
        }
    }
}